const fs = require("fs");
const path = __dirname + "/data.json";
const { fileLog } = require("./log");

function writeData(data, ip) {
    const list = JSON.parse(fs.readFileSync(path).toString());
    list.push({
        time: getTime(),
        text: data,
        ip
    })
    const str = JSON.stringify(list);
    try {
        fs.writeFileSync(path, str);
    } catch (e) {
        fileLog("write data error", e);
        return null;
    }
    return list;
}

function getTime() {
    const now = new Date();
    return `${now.getFullYear()}/${now.getMonth() + 1}/${now.getDate()} ${now.toTimeString().split(" ")[0]}`;
}

function clearData() {
    fs.writeFileSync(path, "[]");
}

function readData(obj) {
    return obj || JSON.parse(fs.readFileSync(path).toString());
}

module.exports = {
    writeData,
    readData,
    clearData,
    getTime
}